package eu.log.db;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import eu.data.util.RollFetchDataSource;
import eu.log.Log;
import eu.log.Rank;

public class QueryDataSource implements RollFetchDataSource<Log> {
	ResultSet rs=null;
	
	QueryDataSource(ResultSet rs) throws SQLException {
		this.rs=rs;
	}

	@Override
	public Log next() {
		try {
			if(rs.next())
				return generateLog(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Collection<Log> next(int size) {
		Collection<Log> logs=new java.util.ArrayList<Log>();
		try {
			while(rs.next()&&size>0){
				logs.add(generateLog(rs));
				size--;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return logs;
	}

	@Override
	public Log previous() {
		try {
			if(rs.previous())
				return generateLog(rs);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public Collection<Log> previous(int size) {
		Collection<Log> logs=new java.util.ArrayList<Log>();
		try {
			while(rs.previous()&&size>0){
				logs.add(generateLog(rs));
				size--;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return logs;
	}

	private Log generateLog(ResultSet rs) throws SQLException{
		return new LogEntity(rs.getString(1),rs.getString(2),
				rs.getTimestamp(3).getTime(),Rank.valueOf(rs.getString(4)));
	}
}
